import React, { useState } from 'react';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Cross2Icon } from '@radix-ui/react-icons';
import styles from './index.module.scss';
import classNames from 'classnames';
import { motion } from 'framer-motion';

const SortableItem = ({
  id,
  index,
  text,
  isEditing,
  isLoading,
  isCompleted,
  onEditStart,
  onEditEnd,
  onDelete,
  onClick,
  disabled,
}) => {
  const [inputValue, setInputValue] = useState(text);
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ 
    id,
    disabled: disabled // Disable drag functionality when disabled prop is true
  });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      onEditEnd(inputValue);
    }
  };

  const handleBlur = () => {
    onEditEnd(inputValue);
  };

  return (
    <div
      ref={setNodeRef}
      style={style}
      className={classNames(styles.item, {
        [styles.dragging]: isDragging,
        [styles.loading]: isLoading,
        [styles.completed]: isCompleted,
        [styles.disabled]: disabled,
      })}
      {...attributes}
    >

      <motion.div 
        className={styles.motion}
        initial={{ opacity: 0 }} // 初始状态：不透明度为 0
        animate={{ opacity: 1 }} // 动画状态：不透明度为 1
        transition={{ duration: 0.5 }} // 动画持续时间为 1 秒
        style={{ height: '100%' }}
      >

        <div className={styles.tag} {...(disabled ? {} : listeners)}>
          {`P${index + 1}`}
        </div>
        
        {isEditing && !disabled ? (
          <input
            type="text"
            className={styles.input}
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyDown={handleKeyDown}
            onBlur={handleBlur}
            autoFocus
          />
        ) : (
          <div className={styles.labelAndDelBtn} onClick={disabled ? undefined : (onClick || onEditStart)}>
            <div className={styles.label}>{text}</div>
            {!disabled && (
              <button
                className={styles.deleteButton}
                onClick={(e) => {
                  e.stopPropagation();
                  onDelete(id);
                }}
              >
                {/* <Cross2Icon /> */}
                <i className="iconfont icon-Delete"></i>
              </button>
            )}
          </div>
        )}

      </motion.div>
    </div>

  );
};

export default SortableItem;
